package hpp.meitu;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

/**
 * Created by hpp on 2017/9/6.
 */
public class Count implements Callable<Map<Integer, Integer>> {

    private String filePath;

    public Count() {
    }

    public Count(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public Map<Integer, Integer> call() throws Exception {
//        System.out.println("filePath = " + filePath);
        return readFileByLine(filePath);
    }

    /**
     * 以行为单位读取文件内容
     *
     * @param filePath
     */
    public Map<Integer, Integer> readFileByLine(String filePath) {

        Map<Integer, Integer> map = new HashMap<>();
        File file = new File(filePath);
        // BufferedReader:从字符输入流中读取文本，缓冲各个字符，从而实现字符、数组和行的高效读取。
        BufferedReader buf = null;

        try (FileWriter fw = new FileWriter("E:\\meituTestFiles\\out\\" + file.getName());
             BufferedWriter bufw = new BufferedWriter(fw);) {
            // FileReader:用来读取字符文件的便捷类。
            buf = new BufferedReader(new FileReader(file));
            // buf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String temp = null;
            String[] bb = null;
            while ((temp = buf.readLine()) != null) {
                String[] aaa = temp.split("\t");
                bb = aaa[1].split("\\|");
                int length = aaa[1].split("\\|").length;
                if (map.containsKey(length)) {
                    map.put(length, map.get(length) + 1);
                } else {
                    map.put(length, 1);
                }

                StringBuilder sb = new StringBuilder();
                sb.append(aaa[0]);
                sb.append("\t");
                if (length > 160) {
                    length = 160;
                }
                for (int i = 0; i < length; i++) {
                    sb.append(bb[i]);
                    if (i != length - 1) {
                        sb.append("|");
                    }
                }
                bufw.write(sb.toString());
                bufw.write("\r\n");
                bufw.flush();
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (buf != null) {
                try {
                    buf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return map;
    }


}
